import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router/index.js'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API

})

// request interceptor
// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // console.dir(error)
    if (error.response.status === 401) {
      // 如果已经在登陆页面了再出现401就直接return了避免重复跳转
      if (router.currentRoute.path === '/login') return
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })

      store.dispatch('user/logOut')
      // ${router.currentRoute.path}:这句代码的意思是退出前在访问的那个页面（固定写法）
      router.replace(`/login?redirect=${router.currentRoute.path}`)
    }
    return Promise.reject(error)
  }
)

export default service
